<?php

namespace backend\models;

use common\logic\UserLogic;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\UserModel;

/**
 * SearchUserModel represents the model behind the search form about `common\models\UserModel`.
 */
class SearchUserModel extends UserModel
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'channel', 'create_time', 'role', 'referee'], 'integer'],
            [['openid', 'union_id', 'nickname', 'mobile', 'avatar'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params,$role=0,$referee=0)
    {
        $query = UserModel::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $this->load($params);

        if(!empty($referee)){
            $query->andWhere(['like' ,  'parent_code' , UserLogic::instance()->getSelfParentCode($referee).'%',false]);
        }else{
            $query->andFilterWhere([
                'role' => $role,
            ]);
        }
        $query->orderBy(['id'=>SORT_DESC]);
        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions

        $query->andFilterWhere(['like', 'nickname', $this->nickname]);
//            ->andFilterWhere(['like', 'union_id', $this->union_id])
//            ->andFilterWhere(['like', 'nickname', $this->nickname])
//            ->andFilterWhere(['like', 'mobile', $this->mobile])
//            ->andFilterWhere(['like', 'avatar', $this->avatar]);

        return $dataProvider;
    }
}
